/*******************************************************************************
 * Copyright (c) 2013 Michele Nanna.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     https://gitorious.org/provinciawifi - initial API and implementation
 *     Michele Nanna - fix some issues
 ******************************************************************************/
package com.systemfastforward.provinciawifi.service;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;

/**
 * Receive Wifi change state, and it reacts when connected on "provinciawifi" SSID Wifi access point launching 
 * WifiAutenthicatorService.
 * 
 * @author https://gitorious.org/provinciawifi
 *
 */
public class WifiBroadcastReceiver extends BroadcastReceiver {
	public static final String DEFAULT_WIFI_SSID = "provinciawifi";

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean isAutoLoginActive = prefs.getBoolean("is_auto_login_active", true);

        if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION) && isAutoLoginActive) {
            NetworkInfo ni = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            WifiManager mWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wInfo = mWifi.getConnectionInfo();
            
            String ssid = prefs.getString("ssid", WifiBroadcastReceiver.DEFAULT_WIFI_SSID);

            if (ni.isConnected() && ssid.equalsIgnoreCase(wInfo.getSSID())) {
                // launch login service
                context.startService(new Intent(context, WifiAuthenticatorService.class));
            }
        }
    }

}
